﻿using System;
using System.Runtime.Serialization;
using System.Xml;
using Core.Shared.Monads;

namespace Core.Logic
{
    public class OptionsManager
    {
        #region Private fields

        private Options.Options _options;

        #endregion

        #region Public methods

        public Options.Options GetOptions()
        {
            return _options.Clone();
        }

        public void UpdateOptions(Options.Options newOptions)
        {
            OnOptionsChanged(newOptions, _options);
            _options = newOptions.Clone();
        }

		public void ForceNotifyOptionsSubscribers()
		{
			OnOptionsChanged(_options, null);
		}

        public void SaveOptions(string path)
        {
            var settings = new XmlWriterSettings { Indent = true };

            using (var writer = XmlWriter.Create(path, settings))
            {
                var serializer = new DataContractSerializer(typeof(Options.Options));
                serializer.WriteObject(writer, _options);
            }
        }

        public void LoadOptions(string path)
        {
            using (var reader = XmlReader.Create(path))
            {
                var deserializer = new DataContractSerializer(typeof(Options.Options));
                _options = (Options.Options)deserializer.ReadObject(reader);
            }
        }

        #endregion

        #region Events

        public event OptionsChangedEventHandler OptionsChanged;

        public void OnOptionsChanged(Options.Options newOptions, Options.Options oldOptions) {
	        OptionsChanged.Do(o => o(this, new OptionsChangedEventArgs(newOptions, oldOptions)));
        }

        public delegate void OptionsChangedEventHandler(object sender, OptionsChangedEventArgs e);

        public class OptionsChangedEventArgs : EventArgs
        {
            public OptionsChangedEventArgs(Options.Options newOptions, Options.Options oldOptions)
            {
                NewOptions = newOptions;
                OldOptions = oldOptions;
            }

            public readonly Options.Options NewOptions;

            public readonly Options.Options OldOptions;
        }

        #endregion
    }
}